package com.zhiliang.waibao.myapplication.module;
import com.zhiliang.waibao.myapplication.MyApp;
import com.zhiliang.waibao.myapplication.net.BaseApi;
import com.zhiliang.waibao.myapplication.net.RetrofitConfig;
import com.zhiliang.waibao.myapplication.net.BaseApiService;

import java.io.File;
import java.util.concurrent.TimeUnit;
import dagger.Module;
import dagger.Provides;
import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Administrator on 2018/3/19.
 */
@Module
public class HttpModule {
    @Provides
    OkHttpClient.Builder provideOkHttpClient() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
//        //包含header、body数据
//        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//        // 指定缓存路径,缓存大小100Mb
        Cache cache = new Cache(new File(MyApp.getsContext().getCacheDir(), "HttpCache"),
                1024 * 1024 * 100);
        return new OkHttpClient().newBuilder().cache(cache)
                .retryOnConnectionFailure(true)
                //http数据log，日志中打印出HTTP请求&响应数据
                .addInterceptor(loggingInterceptor)
                .addInterceptor(RetrofitConfig.sLoggingInterceptor)
                .addInterceptor(RetrofitConfig.sRewriteCacheControlInterceptor)
                .addNetworkInterceptor(RetrofitConfig.sRewriteCacheControlInterceptor)
                .connectTimeout(10, TimeUnit.SECONDS);
    }

    @Provides
    BaseApi provideNetEaseApis(OkHttpClient.Builder builder) {
        Retrofit.Builder retrofitBuilder = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(builder.build());
        return BaseApi.getInstance(retrofitBuilder
                .baseUrl(BaseApi.sIFengApi)
                .build().create(BaseApiService.class));
    }
}
